import { http } from "@/utils/http";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};
/** 添加任务 */
export const addTask = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/add", data);
};

/** 任务详情 */
export const task_detail = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/detail", data);
};

/** 任务开始 */
export const startWorkOrder = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/start", data);
};

/** 任务开始43 */
export const startRemoteWorkOrder = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/start", data);
};

/** 任务暂停 */
export const stopWorkOrder = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/stop", data);
};

/** 任务暂停43 */
export const stopRemoteWorkOrder = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/stop", data);
};

/** 删除任务43 */
export const deleteRemoteTask = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/delete", data);
};

/** 删除任务 */
export const deleteTask = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/delete", data);
};

/** 重新测试43 */
export const retestRemote = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/retest", data);
};

/** 重新测试 */
export const retest = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/retest", data);
};

/** 添加任务 */
export const add_schedule = (data?: object) => {
  return http.request<Result>("post", "/api/schedule/add", data);
};

/** 查询任务 */
export const search_schedule = (data?: object) => {
  return http.request<Result>("post", "/api/schedule/search", data);
};

/** 查询总任务 */
export const task_search = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/data", data);
};
/** 查询总任务43 */
export const task_search_remote = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/data", data);
};

/** 下载任务 */
export const downloadCsv = (data?: object) => {
  return taskRequest<Result>("get", "/api/asset_data/download", data);
};

/** 查询工单 */
export const queryWorkOrder = (data?: object) => {
  return http.request<Result>("post", "/api/work_order/query", { data });
};

/** 编辑工单 */
export const editWorkOrder = (data?: object) => {
  return http.request<Result>("post", "/api/work_order/edit", { data });
};

/** url查询 */
export const scan_result_url = (data?: object) => {
  return http.request<Result>("post", "/api/scan_result_url/search", { data });
};

/** 未报备资产查询 */
export const unreported_asset_scan = (data?: object) => {
  return http.request<Result>("post", "/api/unreported_asset_scan/search", {
    data,
  });
};
/** 未存活资产查询 */
export const non_live_asset_scan = (data?: object) => {
  return http.request<Result>("post", "/api/non_live_asset_scan/search", {
    data,
  });
};
/** 高危端口查询 */
export const high_risk_port = (data?: object) => {
  return http.request<Result>("post", "/api/high_risk_port/search", {
    data,
  });
};

/** 脆弱性查询 */
export const vulScan = (data?: object) => {
  return http.request<Result>("post", "/api/vulScan/search", {
    data,
  });
};

/** 添加远程任务 */
export const addRemoteTask = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/add", data);
};

/** 分析 IP 地址 */
export const analyzeIps = (data?: { assets: string }) => {
  return remoteRequest<Result>("post", "/api/analyze_ips", data);
};

/** 获取模板列表 */
export const getTemplateList = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/task/template/list", data);
};

/** 获取任务模板列表 */
export const getTaskTemplateList = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/task/template/list", data);
};

/** 获取指纹数据 */
export const getFingerprintData = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/fingerprint/data", data);
};

/** 删除指纹数据 */
export const deleteFingerprintData = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/fingerprint/delete", data);
};

/** 新增指纹数据 */
export const addFingerprintData = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/fingerprint/add", data);
};

/** 编辑指纹数据 */
export const updateFingerprintData = (data?: object) => {
  return remoteRequest<Result>("post", "/api/api2/fingerprint/update", data);
};

/** 处理任务 */
export const processTask = (data?: object) => {
  return taskRequest<Result>("post", "/api/task/process_task", data);
};

/** 资产数据统计接口 */
export const getAssetStatistics = (data?: { asset_model_type?: string }) => {
  return http.request<Result>("post", "/api/asset/statistics", {
    data: {
      data: {
        asset_model_type: "exposure",
      },
    },
  });
};

/** 资产批量管理接口 */
export const batchManageAssets = (data?: {
  action: "add" | "delete" | "update";
  asset_model_type?: "exposure" | "application";
  assets: any[];
}) => {
  return http.request<Result>("post", "/api/asset/batch_manage", { data });
};

/** 全量资产同步接口 */
export const syncAllAssets = (data?: { task: string }) => {
  return http.request<Result>("post", "/api/asset/sync_assets", { data });
};

/** 网管资产同步接口 */
export const syncNetworkAssets = (data?: { task: string }) => {
  return http.request<Result>("post", "/api/asset/sync_network_assets", {
    data,
  });
};

/** 资产概览统计接口 */
export const getAssetOverviewStatistics = (data?: { department?: string }) => {
  return taskRequest<Result>("post", "/api/asset/asset_overview_statistics", {
    data,
  });
};

/** 网管资产同步V2接口 */
export const syncAssetsV2 = (data?: { task: string; task_id: number }) => {
  return http.request<Result>("post", "/api/assetManager/sync_assets_v2", {
    data,
  });
};

/** 查询同步状态接口 */
export const getSyncStatus = (data?: { run_id: string }) => {
  return http.request<Result>("post", "/api/assetManager/sync_status", {
    data,
  });
};

/** 查询网管扫描任务列表接口 */
export const queryNetworkTasks = (data?: { page?: number; per_page?: number }) => {
  return http.request<Result>("post", "/api/assetManager/query_task", {
    data,
  });
};

/** 查询同步历史接口 */
export const querySyncHistory = (data?: { task_id: number; page?: number; per_page?: number }) => {
  return http.request<Result>("post", "/api/assetManager/query_sync_history_v2", {
    data,
  });
};

/** 查询比对结果 */
export const querySyncRecords = (data?: {
  run_id: string;
  page?: number;
  per_page?: number;
  exception_type?: string | null;
  ip_search?: string;
}) => {
  return http.request<Result>("post", "/api/assetManager/query_sync_records", {
    data,
  });
};

/** 编辑同步记录（更新或删除） */
export const editSyncRecord = (data?: {
  id: number;
  action: "update" | "delete";
  port?: string;
  exception_type?: string;
  note?: string;
}) => {
  return http.request<Result>("post", "/api/assetManager/edit_sync_record", {
    data,
  });
};

/** 导出修正后的资产表 */
export const exportAsUploadFormat = async (params?: {
  run_id: string;
  exclude_exceptions?: string;
}) => {
  // 直接使用 axios 绕过响应拦截器，避免 Blob 被当作 JSON 处理
  const axios = (await import("axios")).default;
  const { getToken175 } = await import("@/utils/token");
  const token = getToken175();

  const queryParams = new URLSearchParams();
  if (params?.run_id) queryParams.append("run_id", params.run_id);
  if (params?.exclude_exceptions) queryParams.append("exclude_exceptions", params.exclude_exceptions);

  const response = await axios.get(
    `/api/assetManager/export_as_upload_format?${queryParams.toString()}`,
    {
      headers: {
        Authorization: token ? `Bearer ${token}` : undefined,
      },
      responseType: "blob",
    }
  );

  return response.data; // 返回 Blob 对象
};
